package blhorse;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test02 {
    public static void main(String[] args) {
//1.设计一个多线程的程序如下：设计一个火车售票模拟程序。
// 假如火车站要有100张火车票要卖出，现在有5个售票点同时售票，用5个线程模拟这5个售票点的售票情况。
        MyThread t = new MyThread();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);
        Thread t3 = new Thread(t);
        Thread t4 = new Thread(t);
        Thread t5 = new Thread(t);
        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");
        t4.setName("窗口4");
        t5.setName("窗口5");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();

    }
}

class MyThread implements Runnable{
    //synchronized(锁对象)，这个锁对象必须是唯一的
    //票的总量是100张
    int ticket = 0;//票数
    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        //1.循环
        while (true){
            //2.同步代码块 同步方法
            lock.lock();
            try {
                if (ticket == 100){
                    break;
                }else {
                    ticket++;//每一次售一张票
                    System.out.println(Thread.currentThread().getName() + "正在出售第" + ticket + "张票");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

}